package com.ceuer.pet.dao.impl;

import com.ceuer.pet.dao.SpeciesDao;
import com.ceuer.pet.entity.Species;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class SpeciesDaoImpl extends BaseDao implements SpeciesDao {
	
	@Override
	public List<Species> selectAll() {
		List<Species> list= new ArrayList<>();
		Connection connection=null;
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		try {
			String sql="select * from species";
			connection=this.getConn();
			preparedStatement=connection.prepareStatement(sql);
			resultSet=preparedStatement.executeQuery();
			while (resultSet.next()){
				Species species = new Species();
				species.setId(resultSet.getInt("id"));
				species.setName(resultSet.getString("name"));
				
				list.add(species);
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			this.closeAll(connection, preparedStatement, resultSet);
		}
		return list;
	}
	
	@Override
	public Species selectOne(Integer id) {
		Species species=null;
		Connection connection=null;
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		try {
			String sql="select * from species where id=?";
			connection=this.getConn();
			preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setInt(1, id);
			resultSet=preparedStatement.executeQuery();
			while (resultSet.next()){
				species = new Species();
				species.setId(resultSet.getInt("id"));
				species.setName(resultSet.getString("name"));
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			this.closeAll(connection, preparedStatement, resultSet);
		}
		return species;
	}
	
	@Override
	public boolean add(Species species) {
		String sql="insert into species(name) values (?)";
		List<Object> param=new ArrayList<>();
		param.add(species.getName());
		int num=this.executeUpdate(sql,param);
		return num==1;
	}
	
	@Override
	public boolean update(Species species) {
		String sql="update species set name=? where id=?";
		List<Object> param=new ArrayList<>();
		param.add(species.getName());
		param.add(species.getId());
		int num=this.executeUpdate(sql,param);
		return num==1;
	}
}